//code for the first canvas, the welcome/introduction canvas var score;

var stage = new createjs.Stage( "canvas-main" );

var attempts;
var attemptText;
var POLES_COUNT = 3;
var initialPositionX = 60;
var initialPositionY = 480;
var initialVelocityX;
var initialVelocityY;


var timestep = 0;
var delta = .3;


var bucketContainers = new Array();
var bucketsContainer;
var background = new Image();
background.src = "images/b1.jpg";

var backgroundContainer;

//var ball;
var ball = new createjs.Shape();
ball.graphics.beginFill("white").drawCircle(0, 0, 40);

///////
var queue;
// list all your assets here, include an id that can be used to
// refer to the asset in the program and a path for the src
var manifest = [ { id: "pic1", src: "images/b1.jpg"},
		         { id: "pic3", src: "images/f.png"}];

var LOADING_BAR_WIDTH = 600;
var LOADING_BAR_HEIGHT = 40;

// These are global display objects that need to be 
// referenced throughout various preloading functions
var loadingText;
var loadingBar;
var progressValue = 0;
var progressText;
////////

//Audio
var audio1 = document.getElementById("iAudio");
var audio2 = document.getElementById("mAudio");
var audio3 = document.getElementById("pop");

var game = new Game();
game.resetGame();
game.setLevel( 1 );
game.setGameLevel();


// This function draws the default loading screen
// It has text that say Loading... and an empty bar
function drawLoadingView()
{
	document.getElementById('canvas-main').style.display = "inherit";
	document.getElementById('canvas-intro').style.display = "none";
	// draw a preloading screen
	// containers were not used here
	loadingText = new createjs.Text( "Loading...", "30px Arial", "#000000"  );
	loadingText.textBaseline = "alphabetic";
 	loadingText.textAlign= "center";
 	loadingText.x = stage.canvas.width / 2;
	loadingText.y = 200;
	stage.addChild( loadingText );
	
	// draw the progress count
	progressText = new createjs.Text( progressValue + "%", "30px Arial", "#000000"  );
	progressText.textBaseline = "alphabetic";
 	progressText.textAlign= "center";
 	progressText.x = stage.canvas.width / 2;
	progressText.y = 250;
	
	stage.addChild( progressText );
	
	// draw the outline of the bar
	var bar = new createjs.Shape();
	bar.graphics.setStrokeStyle("5").beginStroke( "#000000" );
	bar.graphics.drawRect( 0, 0, LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	
	var barContainer = new createjs.Container();
	barContainer.addChild( bar );
	barContainer.x = stage.canvas.width / 2 - LOADING_BAR_WIDTH / 2;
	barContainer.y = 300;
	
	stage.addChild( barContainer );
	
	// the actual loading bar that grows
	loadingBar = new createjs.Shape();
	loadingBar.graphics.beginFill( "red" );
	loadingBar.graphics.drawRect( stage.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 300, 0, LOADING_BAR_HEIGHT );
	stage.addChild( loadingBar );
	
}

// This function is called when the HTML file is loaded
function preload()
{
	
	drawLoadingView();
		
	// create a new queue of assets that will be loaded
	queue = new createjs.LoadQueue( false );
	
	// important event listeners
	queue.addEventListener( "fileload", handleFileLoad );
	queue.addEventListener( "complete", handleComplete );
	
	queue.installPlugin( createjs.Sound );
	
	// load all images that can possibly be used 
	// this list is a manifest of items with descriptive information
	queue.loadManifest( manifest );
	queue.load();
		
}

function handleFileLoad( evt )
{
	// get the number of items in the manifest 
	var totalProgress = manifest.length; 
	
	progressValue = progressValue + 1;
	
	// draw the progress count by updating the value
	var percentage = Math.ceil( ( progressValue / totalProgress * 100 ) );
	progressText.text = percentage + "%";
	
	// redraw the loading bar
	loadingBar.graphics.beginFill( "blue" );
	loadingBar.graphics.drawRect( stage.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 300, percentage / 100 * LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	stage.update();
}

function handleComplete( evt )
{
	var totalProgress = manifest.length; 
	
	progressValue = progressValue + 1;
	
	// draw the progress count by updating the value
	var percentage = 100;
	progressText.text = percentage + "%";
	
	// redraw the loading bar
	loadingBar.graphics.beginFill( "blue" );
loadingBar.graphics.drawRect( stage.canvas.width / 2 - LOADING_BAR_WIDTH / 2, 300, percentage / 100 * LOADING_BAR_WIDTH, LOADING_BAR_HEIGHT );
	
	var text = new createjs.Text( "Load Complete", "40px Georgia", "orange" );

	text.textAlign = "center";
	text.x = 400;
	text.y = 50;
	
	var containerContinueButton = new createjs.Container();
	
	var continueButton = new createjs.Shape();
	continueButton.graphics.setStrokeStyle( "2" );
	continueButton.graphics.beginStroke( "black" );
	continueButton.graphics.beginFill( "orange" );
	continueButton.graphics.drawRoundRect( 0, 0, 200, 50, 20 );
	

	var continueText = new createjs.Text( "Continue to Game ", "20px Georgia", "White" );
	continueText.textAlign = "center";
	continueText.x = 200 / 2;
	continueText.y = 50 / 3.5;
	

	containerContinueButton.x = 300;
	containerContinueButton.y = 500;
	

	containerContinueButton.addChild( continueButton, continueText );
	containerContinueButton.addEventListener( "click", continueButtonClick );
	
	stage.removeChild(loadingText);
	stage.addChild( text,containerContinueButton );
	stage.update();
	
}

//when the Continue button is clicked on the Preloader canvas, the main canvas is hidden and the main canvas is displayed

function continueButtonClick( evt )
{
	document.getElementById( "canvas-main" ).style.display = "none";
	document.getElementById( "canvas-intro" ).style.display = "inherit";
	document.getElementById( "coordinates" ).style.display = "inherit";
	AudioClick();
	init();
}

//initialize the buckets based on level

function initbucketContainers()
{
	//drawing the buckets

	var numberOfbuckets = game.getNumberOfbuckets();
	var startingX = 450;
	//distances between POLE lines

	var intervalX = Math.floor( (stage.canvas.width - startingX ) / POLES_COUNT - 75 );
	

	for( i = 0; i < numberOfbuckets; i = i + 1 )
		{
			//draw the buckets

			var buckets = new Image();
			buckets.src = "images/f.png";

			bucketsContainer = new createjs.Bitmap( buckets );
			bucketsContainer.x = startingX + intervalX * i - 50 + 7.5;
			bucketsContainer.y = game.getbucketHeights()[ i ];


			bucketContainers.push( bucketsContainer );
		}	
}
//function that is called when the game loads,

//this function calls the introduction screen

function init()

{
	document.getElementById( "coordinates" ).style.display = "none";
	var stage = new createjs.Stage( "canvas-intro" );
		
	AudioIntro();
	
	backgroundContainer = new createjs.Bitmap( background );
	backgroundContainer.x = 0;
	backgroundContainer.y = 0;
	

	var text = new createjs.Text( "Welcome to the Christmas Game", "40px Georgia", "orange" );

	text.textAlign = "center";
	text.x = 400;
	text.y = 50;

	var rules = new createjs.Text( "(Play Hitting the Snowman)\n " + 

			"Type the appropriate number in X and Y coordinates and press the Launch Button. \n"  +
			"Notice: type ( - ) before the number you decided in Y.\n" +

			"Hitting all the snowman then you will move two the next level.\n" +

			"\n You will win when levels are complete.\n"  
			+ "if you run out of all the attempst then it will be Game Over\n" , 

			"19px Georgia", "yellow" );

	rules.textAlign = "center";
	rules.x = 400;
	rules.y = 150;
	//code for the play button container on the welcome/introduction canvas

	var containerPlayButton = new createjs.Container();
	

	var playButton = new createjs.Shape();
	playButton.graphics.setStrokeStyle( "2" );
	playButton.graphics.beginStroke( "black" );
	playButton.graphics.beginFill( "orange" );
	playButton.graphics.drawRoundRect( 0, 0, 200, 50, 20 );
	

	var playText = new createjs.Text( "Start the game ", "20px Georgia", "white" );
	playText.textAlign = "center";
	playText.x = 200 / 2;
	playText.y = 50 / 3.5;
	

	containerPlayButton.x = 300;
	containerPlayButton.y = 500;
	

	containerPlayButton.addChild( playButton, playText );
	containerPlayButton.addEventListener( "click", playButtonClick );
	stage.addChild( backgroundContainer, text, rules, containerPlayButton );
	stage.update();
}

//when the play button is clicked on the welcome canvas, the intro canvas is hidden and the main canvas is displayed

function playButtonClick( evt )
{
	document.getElementById( "canvas-main" ).style.display = "inline";
	document.getElementById( "canvas-intro" ).style.display = "none";
	AudioClick();
	drawMainCanvas();
}
//code for the second canvas, the main canvas where everything is played

function drawMainCanvas()
{
	initbucketContainers();
	drawBackground();
	drawGameStats();
	drawPoleAndbuckets();
	AudioMain();
	document.getElementById( "coordinates" ).style.display = "inherit";

	//adds the ball image to the main-canvas

	var ball = new createjs.Shape();
	ball.graphics.beginFill("white").drawCircle(0, 0, 40);
	
	//ball = new createjs.Bitmap( ball_img );
	
	ball.x = initialPositionX;
	ball.y = initialPositionY;
	
	stage.addChild( ball );
	stage.update();
}
//draws the background image first

function drawBackground()
{
	backgroundContainer = new createjs.Bitmap( background );
	backgroundContainer.x = 0;
	backgroundContainer.y = 0;
	stage.addChild( backgroundContainer );
}
//function to write the user game level, number of attempts, and score.

function drawGameStats()
{
	var scoreText = new createjs.Text( "Score: " + game.getScore(), "18px Georgia", "white" );
	scoreText.textAlign = "left";
	

	var scoreContainer = new createjs.Container();
	scoreContainer.x = 20;
	scoreContainer.y = 10;
	scoreContainer.addChild( scoreText );
	

	var levelText = new createjs.Text( "Level: " + game.getLevel(), "18px Georgia", "white" );
	levelText.textAlign = "left";
	

	var levelContainer = new createjs.Container();
	levelContainer.x = 20;
	levelContainer.y = 30;
	levelContainer.addChild( levelText );
	

	attemptText = new createjs.Text( "Attempts: " + game.getAttempts(), "18px Georgia", "white" );
	attemptText.textAlign = "left";
	

	var attemptContainer = new createjs.Container();
	attemptContainer.x = 100;
	attemptContainer.y = 30;
	attemptContainer.addChild( attemptText );
	

	var formBox = new createjs.DOMElement( "coordinates" );
	document.getElementById( "coordinates" ).style.display = "inline";
	formBox.x = 20;
	formBox.y = 60;
	

	stage.addChild( scoreContainer, levelContainer, attemptContainer, formBox );
}
//Function to draw the Pole lines and buckets after the game level has loaded

function drawPoleAndbuckets()
{
	var numberOfbuckets = game.getNumberOfbuckets();
	var startingX = 450;
	

	var intervalX = Math.floor( (stage.canvas.width - startingX ) / POLES_COUNT - 50 );
	

	for( i = 0; i < numberOfbuckets; i = i + 1 )
		{
			if( game.getbucketHeights()[ i ] != -1 )
				{
					//Draw the Pole lines

					var Pole = new createjs.Shape();
					Pole.graphics.beginLinearGradientFill( [ "black", "white", "blue" ], [ 0, 1, 1 ], startingX + intervalX * i, 0, startingX + intervalX * i + 10, 0 );
					Pole.graphics.drawRect( startingX + intervalX * i, 5, 15, stage.canvas.height );
					

					stage.addChild( Pole );
					

					//Draw the buckets

					var buckets = new Image();
					buckets.src = "images/f.png";
					bucketsContainer = new createjs.Bitmap( buckets );
					bucketsContainer.x = startingX + intervalX * i - 50 + 7.5;
					bucketsContainer.y = game.getbucketHeights()[ i ];
					

					stage.addChild( bucketsContainer );
				}
		}
	stage.update();
}
//function to redraw the canvas

function redraw()
{
	stage.removeAllChildren();
	drawBackground();
	drawGameStats();
	drawPoleAndbuckets();
	stage.addChild( ball );
	stage.update();
}
//the new two function detail what happens as the launch button is clicked.

createjs.Ticker.setFPS( 24 );
 		
function isIntersect()
{
	if( ballContainer.x < bucketsContainer.x + width2 &&
			ballContainer.x + width > bucketsContainer.x &&
			ballContainer.y < bucketsContainer.y + height2 &&
			ballContainer.y + height > bucketsContainer.y )
		{
			return true;
		}
	

}


function tick()

{
	initialVelocityX = document.getElementById( "valueX" ).value;
	initialVelocityY = document.getElementById( "valueY" ).value;
	

	ball.x = initialPositionX + initialVelocityX * timestep;
	ball.y = initialPositionY + initialVelocityY * timestep + .5 * 9.81 * timestep * timestep;
	

	timestep = timestep + delta;
	

	//check collision here//
	
	/*if( isIntersect() )
	{
		var score = game.getScore();
		game.setScore( score + BUCKET_HEIGHT );
		scoreText.text = "Score: " + game.getScore();
		//astroContainer.x = initialPositionX;
		//astroContainer.y = initialPositionY;
		//createjs.Ticker.removeListener( this );
		
	}
else
	{
		//alert( "miss" );
	// check for gameover 
	}
	
	*/

	
	redraw();
		

	if( ball.y > stage.canvas.height || ball.x > stage.canvas.width )
		{
			createjs.Ticker.removeListener( this );
			ball.x = initialPositionX;
			ball.y = initialPositionY;
			timestep = 0;
		}
	stage.update();
}
//function to be called onclick that starts the animation and adjusts the attempts

function launch()
{
	AudioClick();
	var numberOfAttempts = game.getAttempts();
	if( numberOfAttempts > 0 )
		{
			game.setAttempts( numberOfAttempts - 1 );
			attemptText.text = "Attempts: " + game.getAttempts();
			createjs.Ticker.addListener( this );
		}
	else if( numberOfAttempts <= 0 )
		{
			createjs.Ticker.removeListener( this );
			document.getElementById( "canvas-outcome" ).style.display = "inline";

			document.getElementById( "canvas-main" ).style.display = "none";

			drawOutcomeCanvas();

		}
	stage.update();
}


//code for the third canvas, the outcome where winner and/or loser is displayed

function drawOutcomeCanvas()
{
	document.getElementById( "coordinates" ).style.display = "none";
	

	var stage = new createjs.Stage( "canvas-outcome" );
	backgroundContainer;
	

	var outcomeText = new createjs.Text( "You Loss!\n\n", "40px Georgia", "green" );

	outcomeText.text += "Game Over!!";
	outcomeText.textAlign = "center";
	outcomeText.x = 400;
	outcomeText.y = 200;
	stage.addChild( backgroundContainer, outcomeText );
	stage.update();
	

}

//Loads Audio
function AudioIntro(){
	audio2.pause();
	audio1.play();
	audio1.autoplay = true;
	audio1.loop = false;
}

function AudioMain(){
	audio1.pause(); 
	audio2.play();
	audio2.autoplay = true;
	audio2.loop = false;
}

function AudioClick(){
	audio3.play();
}
